package top.maohh.study.demo.zookeeper;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * 连接观察池
 *
 * @author maohh
 */
public class ConnectionWatcher implements Watcher {
    private static final int SESSION_TIMEOUT = 5000;
    protected ZooKeeper zk;
    private CountDownLatch connectedSignal = new CountDownLatch(1);

    /**
     * 连接数据库
     *
     * @param hosts zk地址
     * @throws IOException
     * @throws InterruptedException
     * @throws IOException
     */
    public void connect(String hosts) throws IOException, InterruptedException, IOException {
        zk = new ZooKeeper(hosts, SESSION_TIMEOUT, this);
        connectedSignal.await();
    }

    /**
     * 事件的监听
     *
     * @param event
     */
    @Override
    public void process(WatchedEvent event) {
        if (event.getState() == Event.KeeperState.SyncConnected) {
            System.out.println("zk连接成功.....");
            connectedSignal.countDown();
        }
    }

    /**
     * 关闭zk
     *
     * @throws InterruptedException
     */
    public void close() throws InterruptedException {
        zk.close();
    }

}